package com.xzm.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * map 的链式编程
 * 参考 https://www.cnblogs.com/ziyue7575/p/11738117.html
 * https://www.cnblogs.com/ziyue7575/p/16003339.html
 *
 * @author 瞎琢磨先生 https://github.com/xiazuomo/xzm-utils.git
 * @date 2022/7/29 23:51
 */
@Slf4j
public class MapChainUtils {

    public static void main(String[] args) {
        final Map<String, Integer> map = getMap();

        final MapBuilder<String, Integer> builder = MapChainUtils.builder(map);
        builder.put("2", 22);
        final Map<String, Integer> builderMap = builder.endBuilder();
        System.out.println("builderMap = " + builderMap);
    }

    private static Map<String, Integer> getMap() {

        // // 注意在new的时候，要将具体的泛型类型设置上
        Map<String, Integer> map = new ConcurrentHashMap<String, Integer>() {{
            // 注意是2层的{{
            // put直接使用，不要 map.put(),因为此时map还没有初始化完，会空指针异常
            put("k1", 1);
            put("k2", 2);
        }};

        // final Map<String, Integer> map = new HashMap<>();
        // map.put("1", 1);
        return map;
    }

    public static <K, V> MapBuilder<K, V> builder(Map<K, V> map) {
        return MapBuilder.builder(map);
    }

    public static class MapBuilder<K, V> {
        private final Map<K, V> map;

        private MapBuilder(Map<K, V> map) {
            this.map = map;
        }

        public static <K, V> MapBuilder<K, V> builder(Map<K, V> map) {
            return new MapBuilder<K, V>(map);
        }

        public Map<K, V> endBuilder() {
            return map;
        }

        public MapBuilder<K, V> put(K k, V v) {
            map.put(k, v);
            return this;
        }

    }
}
